<template>
	<view>
		<Navbar></Navbar>
		<view class="u-form-box u-m-30">
			<u-form :model="form" label-width="200" ref="form1">
				<u-form-item required label="姓名">
					<u-input placeholder="请输入真实姓名" input-align="right" :clearable="false" v-model="form.name" />
				</u-form-item>
				<u-form-item required label="公司名称">
					<view :class="form.company ? '' : 'u-color-gray'">
						<u-input :clearable="false" input-align="right" placeholder="请输入公司完整名称"
							v-model="form.company"></u-input>
					</view>
				</u-form-item>
				<u-form-item required label="职位">
					<u-input placeholder="请输入职位" v-model="form.position" :clearable="false" input-align="right" />
				</u-form-item>
				<u-form-item required="true" label="城市">
					<view class="u-text-right" :class="form.hometown ? '' : 'u-color-placeholder'"
						@click="onOpenHomeTown">
						{{ form.hometown || '请选择常驻城市 >'}}
					</view>
				</u-form-item>
				<u-form-item label="身份证号" prop="id_card">
					<u-input v-model="form.id_card" placeholder="请输入身份证号码" maxlength="18" input-align="right"
						:clearable="false" />
				</u-form-item>
				<!-- <u-form-item label="合伙人推荐人">
					<view class="u-text-right u-text-line-15 reference_name"
						:class="reference.name ? '' : 'u-color-gray'" @click="openReference">
						{{ reference.name || '请选择合伙人推荐人 >'}}
					</view>
				</u-form-item> -->
			</u-form>
		</view>
		<view class="u-font-34 u-font-bold u-m-30">收货信息</view>
		<view class="u-p-30 u-m-30 u-font-bold u-form-box u-relative">
			<view class="require u-flex u-row-between" v-if="addressData.id">
				<view>
					<view>{{ addressData.city }}</view>
					<view class="u-m-t-5 u-m-b-5 u-font-38">{{ addressData.address }}</view>
					<view>
						<span class="u-m-r-5">{{ addressData.name }}</span>
						<span>{{ addressData.phone }}</span>
					</view>
				</view>
				<view class="u-m-l-20" @click="onEditAddress(addressData.id)">
					<u-icon name="edit-pen" size="40"></u-icon>
				</view>
			</view>
			<view class="require u-flex u-row-between" @click="onSwitchAddress()" v-else>
				<view class="u-font-bold">暂无收货信息，点击新建</view>
				<u-icon name="arrow-right"></u-icon>
			</view>
		</view>
		<!-- <view class="u-font-34 u-font-bold u-m-30">收款信息</view>
		<view class="u-form-box u-m-30">
			<u-form :model="form" label-width="240" ref="form2">
				<u-form-item required label="账户姓名">
					<u-input placeholder="请输入收款账户真实姓名" input-align="right" :clearable="false"
						v-model="form.bank_name" />
				</u-form-item>
				<u-form-item required label="账户银行及支行">
					<u-input placeholder="请输入收款账户银行及支行" input-align="right" :clearable="false" v-model="form.bank" />
				</u-form-item>
				<u-form-item required label="账户账号">
					<u-input placeholder="请输入收款账户账号" v-model="form.bank_account" type="number" :clearable="false"
						input-align="right" />
				</u-form-item>
				<u-form-item required="true" label="手机号码">
					<view class="u-text-right">
						<view class="u-flex">
							<view class="country_code" @click="codeShow = true">
								<text class="u-p-r-10">+{{ form.bank_area_code }}</text>
								<u-icon name="arrow-right" size="26" color="#c0c4cc"></u-icon>
							</view>
							<u-input placeholder="请输入收款账户人手机号" v-model="form.bank_phone" type="number"
								:clearable="false" input-align="right" />
						</view>
					</view>
				</u-form-item>
				<u-form-item required label="身份证号" prop="bank_id_card">
					<u-input v-model="form.bank_id_card" placeholder="请输入收款账户人身份证号码" maxlength="18" input-align="right"
						:clearable="false" />
				</u-form-item>
			</u-form>
		</view> -->
		<view style="height: 200rpx;"></view>
		<!-- <Bottom :isTwice="true" :isClick="isClick" :rightText="btnText" @confirm="confirm"></Bottom> -->
		<view class="bottom_box">
			<view class="u-width-100 u-flex u-row-between">
				<view class="confirm_btn u-m-r-30 common_css u-flex-1" @click="onBankText">{{bankText}}</view>
				<view class="confirm_btn common_css u-flex-1" @click="onWechatPay">{{btnText}}</view>
			</view>
		</view>

		<!-- 城市 -->
		<UniAddressSelector v-if="addressShow" :selectAreaLevelLimit="2" :isSZ="0" @cancel="onCloseHomeTown"
			@confirm="onConfirmArea"></UniAddressSelector>

		<!-- 区号 -->
		<view v-if="codeShow">
			<u-select v-model="codeShow" @confirm="onCodeConfirm" :default-value="[0]" :mask-close-able="false"
				value-name="area_code" :list="codeList"></u-select>
		</view>

		<!-- 入群二维码 -->
		<u-popup v-model="joinCode.show" mode="center" border-radius="20" :mask-close-able="false" :closeable="true"
			close-icon-size="40" width="90%" @close="onCloseJoinCode">
			<view class="u-p-20 u-p-t-60">
				<view class="u-m-t-20 u-m-b-20 u-font-bold u-font-32 u-text-center">请扫码添加负责人，参加青创私董培训</view>
				<u-image class="u-m-t-20 u-width-100" :src="joinCode.image" mode="widthFix"></u-image>
			</view>
		</u-popup>

		<!-- 推荐人 -->
		<u-popup v-model="reference.show" mode="bottom" border-radius="20">
			<view class="checkAddressBox">
				<u-search v-model="reference.keyword" placeholder="请输入推荐人关键词" @search="searchReference"
					@clear="clearReference" @custom="searchReference"></u-search>
				<scroll-view scroll-y="true" style="height: 700rpx;margin-bottom: 60rpx;"
					@scrolltolower="loadReference">
					<view class="slot-content">
						<view :class="item.check ? 'address_check_box' : 'address_box'" v-for="item in reference.list"
							:key="item.id">
							<view @click="checkReference(item)">{{item.name}}</view>
						</view>
					</view>
				</scroll-view>
				<view class="u-flex">
					<view class="addBtn" @click="reference.show = false">取消</view>
					<view class="bottomBtn" @click="confirmReference">确定</view>
				</view>
			</view>
		</u-popup>
	</view>
</template>

<script>
	import Navbar from "@/components/Navbar.vue";
	import Bottom from '@/components/Bottom.vue'
	import UniAddressSelector from '@/components/UniAddressSelector.vue'
	import {
		userInfo,
		phoneAreaCode,
		getConfigInfo
	} from '@/network/api.js'
	import {
		teaPresidentEcho,
		teaCreateOrder,
		teaOrderSn,
		presidentList
	} from '@/network/tea.js'
	import {
		hasEmptyValue
	} from '@/utils/index.js'
	export default {
		components: {
			Navbar,
			Bottom,
			UniAddressSelector
		},
		data() {
			return {
				form: {
					name: '',
					company: '',
					position: '',
					hometown: '',
					id_card: '',
					province_id: 0,
					city_id: 0,
					// bank_name: '', // 收款账户姓名
					// bank: '', // 收款银行
					// bank_account: '', // 收款账号
					// bank_phone: '', // 收款手机号
					// bank_area_code: '86', // 收款区号
					// bank_id_card: '', // 收款身份证号
				},
				addressData: {},
				joinCode: {
					show: false,
					image: ''
				},
				// 推荐人
				reference: {
					show: false,
					keyword: '',
					list: [],
					page: 1,
					pageSize: 10,
					status: 0, // 0 可选择 1 不可选择
					name: '',
					id: '',
					inviteId: '' // 青创私董邀请注册通道
				},
				// 身份证验证
				rules: {
					id_card: [{
							required: false,
							message: '请输入身份证号',
							trigger: ['blur', 'change']
						},
						{
							validator: (rule, value, callback) => {
								// 身份证正则表达式
								const idCardRegex =
									/^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[012]))(([0|1|2]\d)|3[01])\d{3}([0-9]|X|x)$/;
								return idCardRegex.test(value);
							},
							message: '身份证格式不正确',
							trigger: ['blur', 'change']
						}
					],
				},
				rules2: {
					bank_id_card: [{
							required: true,
							message: '请输入身份证号',
							trigger: ['blur', 'change']
						},
						{
							validator: (rule, value, callback) => {
								// 身份证正则表达式
								const idCardRegex =
									/^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[012]))(([0|1|2]\d)|3[01])\d{3}([0-9]|X|x)$/;
								return idCardRegex.test(value);
							},
							message: '身份证格式不正确',
							trigger: ['blur', 'change']
						}
					]
				},
				btnText: '微信支付',
				bankText: '银行转账',
				isClick: true,
				isHometown: true, // 是否可选择
				codeShow: false,
				codeList: [],
				formPrice: 0,
				addressShow: false,
				userId: uni.getStorageSync("user_id")
			}
		},
		async onLoad(options) {
			if (options.id) {
				this.reference.inviteId = options.id
				const res = await userInfo({
					user_id: options.id
				})
				this.reference.name = res.data.name
				this.reference.id = res.data.id
				this.reference.status = 1
			}
			this.onGetCountryCode()
			this.getJoinCodeImage()
		},
		onShow() {
			this.onGetPrice()
			this.onGetUserInfo()
		},
		onReady() {
			// this.$refs.form1.setRules(this.rules);
			// this.$refs.form2.setRules(this.rules2);
		},
		methods: {
			async onGetPrice() {
				const res = await getConfigInfo({
					key: 'form_recommend'
				})
				this.formPrice = res.data.value
				this.btnText = `微信支付${res.data.value}元`
				this.bankText = `银行转账${res.data.value}元`
			},
			async onGetUserInfo() {
				const params = {
					user_id: this.userId,
					type: 2
				}
				const res = await teaPresidentEcho(params)
				const userRes = await userInfo({
					user_id: this.userId
				})
				// 有回显并且用户有推荐人绑定关系
				if (res.data && res.data.reference_id) {
					this.reference.id = res.data.reference_arr.id
					this.reference.name = res.data.reference_arr.name
				}
				// 没有回显并且用户有推荐人绑定关系
				if(!res.data && userRes.data.reference_id){
					this.reference.id = userRes.data.reference_id
					this.reference.name = userRes.data.reference_name
					this.reference.status = 1
				}
				// 有回显、回显没有推荐人、用户有推荐人
				if(res.data && !res.data.reference_id && userRes.data.reference_id){
					this.reference.id = userRes.data.reference_id
					this.reference.name = userRes.data.reference_name
					this.reference.status = 1
				}
				// 判断是否有城市
				if([5,6,7,8,9].includes(userRes.data.president_status) && userRes.data.native){
					this.form.hometown = userRes.data.native
					this.form.province_id = userRes.data.province_id
					this.form.city_id = userRes.data.city_id
					this.isHometown = false
				}
				this.userData = res.data ? res.data : userRes.data
				this.form.name = this.userData.name
				this.form.company = this.userData.company
				this.form.position = this.userData.position
				this.form.id_card = this.userData.id_card
				if (userRes.data.user_add.is_have == 1) {
					this.addressData = userRes.data.user_add.add
					this.addressData.city = this.addressData.address.substring(0, this.addressData.address.indexOf(
						"区") + 1)
					this.addressData.address = this.addressData.address.substring(this.addressData.address.indexOf(
						"区") + 1, this.addressData.address.length)
				}
			},
			async onGetCountryCode() {
				const res = await phoneAreaCode()
				res.data.forEach(item => {
					item.label = item.name + '+' + item.area_code
				})
				this.codeList = res.data
			},
			async getJoinCodeImage() {
				const res = await getConfigInfo({key: 'join_code_two'})
				this.joinCode.image = res.data.value
			},
			onGetPresidentList() {
				const params = {
					is_president: 1,
					keyword: this.reference.keyword,
					page: this.reference.page,
					limit: this.reference.pageSize
				}
				presidentList(params).then(res => {
					res.data.list.map(item => {
						const params = {
							...item,
							check: false
						}
						this.reference.list.push(params)
					})
				})
			},
			openReference() {
				if(this.reference.status == 1){
					return
				}else{
					this.reference.show = true
				}
			},
			searchReference() {
				this.reference.list = []
				this.reference.page = 1
				if (this.reference.keyword) {
					this.onGetPresidentList()
				} else {
					uni.showToast({
						title: "请输入推荐人关键词",
						icon: "none"
					})
				}
			},
			clearReference() {
				this.reference.keyword = ''
				this.reference.list.length = 0
				this.reference.page = 1
				this.onGetPresidentList()
			},
			loadReference() {
				this.reference.page++
				this.onGetPresidentList()
			},
			checkReference(val) {
				this.reference.list.map(item => item.check = false)
				val.check = true
			},
			confirmReference() {
				let checkObj = this.reference.list.find(item => item.check == true)
				this.reference.name = checkObj.name
				this.reference.id = checkObj.id
				this.reference.show = false
			},
			onCodeConfirm(val) {
				this.form.bank_area_code = val[0].value
			},
			onSwitchAddress() {
				uni.navigateTo({
					url: "/teaBureau/teaAddressList/teaAddressList?type=1"
				})
			},
			onEditAddress(id) {
				uni.navigateTo({
					url: "/teaBureau/teaAddressForm/teaAddressForm?id=" + id
				})
			},
			onCloseJoinCode() {
				uni.switchTab({
					url: "/pages/mine/mine"
				})
			},
			onOpenHomeTown() {
				if(this.isHometown){
					this.addressShow = true
				}
			},
			onCloseHomeTown() {
				this.addressShow = false;
			},
			onConfirmArea(val) {
				this.addressShow = false;
				this.form.province_id = val.provinceObj.areaCode
				this.form.city_id = val.cityObj.areaCode
				this.form.hometown = val.fullAreaText
			},
			async onBankText(){
        let formNew = {...this.form}
        delete formNew.id_card
				if (hasEmptyValue(formNew) && this.isClick) {
					this.isClick = false
					// 收货信息
					if(this.addressData.id){
						const _this = this
						const params = {
							...this.form,
							reference_id: this.reference.id,
							user_id: uni.getStorageSync("user_id")
						}
						const orderRes = await teaOrderSn()
						const orderParams = {
							type: 'partner',
							order_sn: orderRes.data.order_sn,
							userid: uni.getStorageSync("user_id"),
							price: this.formPrice,
							pay_type: 1,
							params: JSON.stringify(params)
						}
						const res = await teaCreateOrder(orderParams)
						this.isClick = true
						uni.setStorageSync("bank",res.data)
						uni.navigateTo({
							url: "/teaBureau/teaBankOrder/teaBankOrder"
						})
					}else{
						uni.showToast({
							title: "请完善收货信息",
							icon: "none"
						})
						this.isClick = true
					}
				} else {
					uni.showToast({
						title: "必填项不能为空",
						icon: "none"
					})
					this.isClick = true
				}
			},
			async onWechatPay() {
        let formNew = {...this.form}
        delete formNew.id_card
        console.log(formNew);
        console.log(this.isClick);
				if (hasEmptyValue(formNew)  && this.isClick) {
					this.isClick = false
					// 收货信息
					if(this.addressData.id){
						const _this = this
						const params = {
							...this.form,
							reference_id: this.reference.id,
							user_id: uni.getStorageSync("user_id")
						}
						const orderRes = await teaOrderSn()
						const orderParams = {
							type: 'partner',
							order_sn: orderRes.data.order_sn,
							userid: uni.getStorageSync("user_id"),
							price: this.formPrice,
							pay_type: 2,
							params: JSON.stringify(params)
						}
						const res = await teaCreateOrder(orderParams)
						await uni.requestPayment({
							provider: "wxpay",
							appId: res.data.order_str.appId,
							timeStamp: res.data.order_str.timeStamp,
							nonceStr: res.data.order_str.nonceStr,
							package: res.data.order_str.package,
							signType: res.data.order_str.signType,
							paySign: res.data.order_str.paySign,
							success() {
								_this.joinCode.show = true
							},
							fail(err) {
								_this.isClick = true
								uni.hideLoading()
								uni.showLoading({
									title: err,
								})
							},
							complete() {
								_this.isClick = true
								uni.hideLoading()
							}
						})
					}else{
						uni.showToast({
							title: "请完善收货信息",
							icon: "none"
						})
						this.isClick = true
					}
				} else {
					uni.showToast({
						title: "必填项不能为空",
						icon: "none"
					})
					this.isClick = true
				}
			}
		}
	}
</script>

<style lang="scss" scoped>
	.checkAddressBox {
		height: 1000rpx;
		padding: 30rpx 30rpx 50rpx 30rpx;

		.address_box {
			padding: 20rpx;
			margin-top: 20rpx;
			border-radius: 10rpx;
			background: #FAFAFA;
		}

		.address_check_box {
			padding: 20rpx;
			margin-top: 20rpx;
			border-radius: 20rpx;
			background: #fb6316;
			color: #fff;
		}

		.addBtn {
			flex: 1;
			height: 80rpx;
			background: #fff;
			color: #000;
			border-radius: 50rpx;
			display: flex;
			justify-content: center;
			align-items: center;
			font-size: 26rpx;
			margin-right: 40rpx;
			border: 1rpx solid #ccc;
		}

		.bottomBtn {
			flex: 1;
			height: 80rpx;
			background: #fb6316;
			color: #fff;
			border-radius: 50rpx;
			display: flex;
			justify-content: center;
			align-items: center;
			font-size: 26rpx;
		}
	}
	
	.require::before {
		content: "*";
		color: #F8494D;
		top: 30rpx;
		position: absolute;
		left: 10rpx;
	}
	
	.common_css{
		color:#fff;
		display: flex;
		justify-content: center;
		align-items: center;
		font-size: 26rpx;
	}
	
	.confirm_btn{
		height: 80rpx;
		background: #B3723E;
		border-radius: 50rpx;
	}
</style>